package com.train.mgr.modules.biz.controller;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.json.JSONUtil;
import com.train.common.enums.ResultEnum;
import com.train.common.exception.BusinessException;
import com.train.common.model.R;
import com.train.common.utils.AssertUtil;
import com.train.mgr.modules.biz.dto.response.FileDto;
import com.train.mgr.modules.biz.service.IFileUploadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 上传文件 通用控制器
 *
 * @date 2021/10/28 16:51
 */
@Api(value = "UploadController", tags = "统一上传文件")
@Slf4j
@RestController
@RequestMapping("/upload")
public class UploadController {

    @Autowired
    private IFileUploadService fileUploadService;

    /**
     * 上传文件至应用服务器
     * @param files
     */
    @ApiOperation("上传文件接口")
    @PostMapping(value = "/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiImplicitParam(name = "files", value = "formData类型接收文件", required = true, dataTypeClass = File.class)
    public R<List<FileDto>> uploadLocal(@RequestPart(name = "files") MultipartFile[] files,
                                        @RequestParam(name = "busiType", required = false,defaultValue = "") String busiType) {
        AssertUtil.isTrue(ArrayUtil.isEmpty(files), ResultEnum.PARAM_EMPTY.getCode()+"", "上传文件不能为空");

        List<FileDto> uploadFileList = new ArrayList<>(files.length);
        Arrays.stream(files).forEach(file -> {
            try {
                uploadFileList.add(fileUploadService.uploadLocal(file,busiType));
            } catch (Exception e) {
                log.error("uploadFile error", e);
                throw new BusinessException(e.getMessage());
            }
        });
        log.info("上传文件接口 uploadFileList:{}", JSONUtil.toJsonStr(uploadFileList));
        return R.succeed(uploadFileList);
    }


}
